package com.yonyou.pmclouds.auditlog.rmiimpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.auditlog.entity.AuditLogVO;
import com.yonyou.pmclouds.auditlog.mapper.AuditLogMapper;
import com.yonyou.pmclouds.auditlog.service.IAuditLogQuery;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.picture.rmiitf.PictureRemoteService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * @author th
 * @date 2019/10/25 11:27
 */
@Service(interfaceClass = IAuditLogQuery.class, version = ApplicationConsts.APPLICATION_VERSION)
public class AuditLogQueryImpl implements IAuditLogQuery {
    @Autowired
    private AuditLogMapper mapper;
    @Autowired
    private PictureRemoteService pictureQuery;

    @Override
    public AuditLogVO getById(String id) throws BusinessException {
        if (StringUtils.isEmpty(id))
            return null;

        AuditLogVO logVO = mapper.getById(id);
        if (logVO == null)
            return null;

        logVO.setPictures(pictureQuery.queryPicNamesByPkEntity(logVO.getPkAuditLog()));
        return logVO;
    }

    @Override
    public AuditLogVO getByPkRepairLog(String pkRepairLog) throws BusinessException {
        if (StringUtils.isEmpty(pkRepairLog))
            return null;

        AuditLogVO logVO = mapper.getByPkRepairLog(pkRepairLog);
        if (logVO == null)
            return null;

        logVO.setPictures(pictureQuery.queryPicNamesByPkEntity(logVO.getPkAuditLog()));
        return logVO;
    }

    @Override
    public Map<String, AuditLogVO> getByPkBill(String pkBill) throws BusinessException {
        Map<String, AuditLogVO> resultMap = new HashMap<>();
        if (StringUtils.isEmpty(pkBill))
            return resultMap;

        // 查询验收记录
        List<AuditLogVO> auditLogVOS = mapper.getByPkBill(pkBill);
        if (CollectionUtils.isEmpty(auditLogVOS))
            return resultMap;

        Set<String> pkAuditLogSet = new HashSet<>();
        for (AuditLogVO logVO : auditLogVOS) {
            if (logVO != null)
                pkAuditLogSet.add(logVO.getPkAuditLog());
        }

        // 查询图片
        Map<String, List<String>> pictureMap = pictureQuery.queryPicsByPkEntitys(pkAuditLogSet.toArray(new String[0]));
        if (pictureMap != null) {
            List<String> pictures;
            for (AuditLogVO vo : auditLogVOS) {
                pictures = pictureMap.get(vo.getPkAuditLog());
                if (CollectionUtils.isNotEmpty(pictures)) {
                    vo.setPictures(pictures.toArray(new String[0]));
                }
                resultMap.put(vo.getPkRepairLog(), vo);
            }
        }

        return resultMap;
    }

}
